package com.ckzp.jfinal.weixin.util;

import com.alibaba.fastjson.JSON;
import com.ckzp.core.util.*;
import com.ckzp.jfinal.weixin.model.WxMember;
import com.ckzp.weixin.AccessTokenTool;
import com.ckzp.weixin.PageSite;
import com.ckzp.weixin.WxTool;
import com.ckzp.weixin.model.WxUser;
import com.ckzp.weixin.model.WxUserToken;
import com.jfinal.kit.HttpKit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * Created by 51594 on 2022/9/22.
 */
public class WxUserUtil {

    public static WxUserUtil n() {
        return new WxUserUtil();
    }


    /**
     * @param request
     * @return
     */
    public WxUser initWxUserUnion(HttpServletRequest request, HttpServletResponse response) {
        String code = ParamUtil.getString(request, "code", "");
        String state = ParamUtil.getString(request, "state", "");
        String jwt = ParamUtil.getString(request, "jwt", "");
        int user_id = JwtUtil.getUserId(jwt);
        if (user_id == 0) user_id = PageSite.getU_ID(request);
        WxMember u = WxMember.dao.findById(user_id);
        WxUser user = new WxUser();
        if (u == null) {
            if (code.length() > 0 || "9981".equals(state)) {
                WxUserToken userToken = getWxToken(code);
                String openid = userToken.getOpenid();
                String unionid = getUserUnionId(openid);
                userToken.setUnionid(unionid);
                //////////////////////////////
                if (unionid != null) {
                    WxMember member = WxMember.dao.findFirst("select * from wx_member where union_id=?", unionid);
                    if (member != null) {
                        member.set("open_id", openid).update();
                        user.setOpen_id(member.mod.getStr("open_id", ""));
                        user.setUser_id(member.mod.getInt("mem_id", 0));
                        user.setIs_check(1);
                    }
                }
                user.setOpen_id("code--" + code + "====" + userToken.toJson());
                user.setIs_check(1);
            }
        } else {
            user.setOpen_id(u.mod.getStr("open_id", ""));
            user.setUser_id(user_id);
            user.setIs_check(1);
        }
        return user;
    }


    /**
     * @param request
     * @return
     */
    public WxUser initWxUser(HttpServletRequest request, HttpServletResponse response) {
        String code = ParamUtil.getString(request, "code", "");
        String state = ParamUtil.getString(request, "state", "");
        String jwt = ParamUtil.getString(request, "jwt", "");
        int user_id = JwtUtil.getUserId(jwt);
        if (user_id == 0) user_id = PageSite.getU_ID(request);
        WxMember u = WxMember.dao.findById(user_id);
        WxUser user = new WxUser();
        if (u == null) {
            if (code.length() > 0 || "9981".equals(state)) {
                WxUserToken userToken = getWxToken(code);
                String openid = userToken.getOpenid();
                //////////////////////////////
                if (openid != null) {
                    WxMember member = WxMember.dao.findFirst("select * from wx_member where open_id=?", openid);
                    if (member != null) {
                        member.set("open_id", openid).update();
                        user.setOpen_id(member.mod.getStr("open_id", ""));
                        user.setUser_id(member.mod.getInt("mem_id", 0));
                    } else {
                        member = new WxMember().set("open_id", openid);
                        Date cdate = new Date();
                        int yymmdd = DateUtil.getYYYYMMDD(cdate);
                        member.set("mem_ip", ClientUtil.getIp(request));
                        member.set("c_date", cdate);
                        member.set("c_dateint", yymmdd);
                        member.save();
                        user.setOpen_id(openid);
                        user.setUser_id(member.getInt("mem_id"));
                    }
                }
                /////////////////////////////////////////////
                user.setIs_check(1);
            }
        } else {
            user.setOpen_id(u.mod.getStr("open_id", ""));
            user.setUser_id(user_id);
            user.setIs_check(1);
        }
        return user;
    }

    /**
     * 根据 CODE取得用户的OPENID
     *
     * @param code
     * @return
     */
    public WxUserToken getWxToken(String code) {
        String appid = WxTool.getAppID();
        String appsecret = WxTool.getAppSecret();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + appid + "&secret=" + appsecret + "&code=" + code + "" +
                "&grant_type=authorization_code";
        String result = HttpKit.get(url);
        Object o = JSON.parseObject(result, WxUserToken.class);
        if (o instanceof WxUserToken) {
            return (WxUserToken) o;
        } else {
            return new WxUserToken();
        }
    }


    /**
     * https://developers.weixin.qq.com/doc/offiaccount/User_Management/Get_users_basic_information_UnionID.html
     *
     * @param openid
     * @return
     */
    public static String getUserUnionId(String openid) {
        String ACCESS_TOKEN = AccessTokenTool.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + ACCESS_TOKEN + "&openid=" + openid + "&lang=zh_CN";
        String result = HttpKit.get(url);
        Map m = JSON.parseObject(result, Map.class);
        return StringUtil.getString(m, "unionid");
    }
}